package com.puppet.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.puppet.pojo.Book;
import com.puppet.pojo.Result;
import com.puppet.pojo.entity.RedisConst;
import com.puppet.pojo.vo.BookVO;
import com.puppet.service.BookService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookService bookService;
    //测试案例
    @PostMapping
    public List<Book> getAllBook(){
        //获取所有书籍
        return bookService.list();
    }
@PostMapping("/getBookByTypeId/{typeId}/{currentPage}/{pageSize}")
@Cacheable(value = RedisConst.BOOK_LIST,keyGenerator= "keyGenerator")
    public Result getBookByTypeId(
            @PathVariable("typeId") int typeId,
            @PathVariable("currentPage") int currentPage,
            @PathVariable("pageSize") int pageSize
){
    Page<Book> page = new Page<>(currentPage, pageSize);
    QueryWrapper<Book> wrapper = new QueryWrapper<>();
    wrapper.eq("type_id",typeId);
    Page<Book> bookPage = bookService.page(page, wrapper);
    List<Book> books = bookPage.getRecords();
    List<BookVO> bookVOS = new ArrayList<>();
    books.forEach(book -> {
        BookVO bookVO = new BookVO();
        BeanUtils.copyProperties(book,bookVO);
        bookVOS.add(bookVO);
    });
    //封装数据和总记录数到 Map 中，再返回 Result
    Map<String, Object> resultMap = new HashMap<>();
    resultMap.put("obj", bookVOS);
    resultMap.put("total", bookPage.getTotal());
    return Result.ok(resultMap);
}
}
